﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;

namespace KingSite.Library.Security {

    public class ConnStringEncrypt {
        /// <summary>
        /// 获取解密后的连接字符串
        /// </summary>
        /// <param name="connectionStringName">连接字符串的配置节名称</param>
        /// <param name="dbEncryptkeyPathFile">数据库连接串加密key文件</param>
        /// <returns></returns>
        public static string GetConnString(string connectionStringName, string dbEncryptkeyPathFile) {

            string connstr = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; 
            if (string.IsNullOrEmpty(connstr)) {
                throw new Exception(string.Format("Not found database connection string section {0} !", connectionStringName));
            }

            if (!File.Exists(dbEncryptkeyPathFile)) {
                throw new Exception(string.Format("Not found file {0} !", dbEncryptkeyPathFile));
            }

            string key = File.ReadAllText(dbEncryptkeyPathFile);
            if (string.IsNullOrEmpty(key)) {
                throw new Exception(string.Format("Key can not be emtpy!", dbEncryptkeyPathFile));
            }

            string result = AES.Decrypt(connstr, key, 128);
            return result;
        }
    }
}
